package com.wy.framework.filters;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class InvalidCharacterUrlFilter implements Filter {
	private static Logger logger = LoggerFactory.getLogger(InvalidCharacterUrlFilter.class);
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest httprequest = (HttpServletRequest)request;
		httprequest.setCharacterEncoding("utf-8");
		String uri = httprequest.getRequestURI();
		String paramStr = httprequest.getQueryString();

		//对URL进行分析
		String decodeUri ="";
		try{
		  decodeUri = URLDecoder.decode(uri+"?"+(paramStr==null?"":paramStr),"utf-8").toLowerCase();
		}catch(Exception e){
			response.setCharacterEncoding("gb2312");
			response.getWriter().write("<html><center style='padding-top:100px'><span style='color:red'>错误的 URL 请求!</span></center></html>");
		    return;
		}
		if(decodeUri.contains("<")||decodeUri.contains(">")||decodeUri.contains("expression")||decodeUri.contains("script")){
			writeError(response,decodeUri);
		}else{
			//验证提交的表单是否含有特殊字符
			Map formValues = request.getParameterMap();
		    Set<Map.Entry> set = formValues.entrySet();
			if(formValues!=null){
				for (Iterator<Map.Entry> it = set.iterator(); it.hasNext();) {
					Map.Entry entry = (Map.Entry) it.next();
					// 富文本框不校验
					if (entry.getKey().toString().contains("contents") || entry.getKey().toString().contains("content")) {
						continue;
					}
					Object obj = entry.getValue();
					if (obj instanceof String[]) {
						String[] strs = (String[]) obj;
						for (int i = 0; i < strs.length; i++) {
							strs[i] = strs[i].replaceAll("'", "’");
							String str = strs[i];

							if (str.indexOf("<") > -1) {
								writeError(response, str);
								return;
							}

							if (str.indexOf("%3C") > -1) {
								writeError(response, str);
								return;
							}

							if (str.indexOf(">") > -1) {
								writeError(response, str);
								return;
							}

							if (str.indexOf("%3E") > -1) {
								writeError(response, str);
								return;
							}

							if (str.toLowerCase().indexOf("script") > -1) {
								writeError(response, str);
								return;
							}

							if (str.toLowerCase().indexOf("expression") > -1) {
								writeError(response, str);
								return;
							}
						}
					}
				}
				  
//				for(Iterator it= formValues.values().iterator();it.hasNext();){
//					Object obj = it.next();
//					if(obj instanceof String[]){
//						String[] strs= (String[])obj;
//						for(int i=0;i<strs.length;i++){
//							strs[i]=strs[i].replaceAll("'", "’");
//							String str = strs[i];
//
//							if(str.indexOf("<")>-1){
//								writeError(response,str);
//								return;
//							}
//							
//							if(str.indexOf("%3C")>-1){
//								writeError(response,str);
//								return;
//							}
//							
//							if(str.indexOf(">")>-1){
//								writeError(response,str);
//								return;
//							}
//							
//							if(str.indexOf("%3E")>-1){
//								writeError(response,str);
//								return;
//							}
//
//							if(str.toLowerCase().indexOf("script")>-1){
//								writeError(response,str);
//								return;
//							}
//							
//							if(str.toLowerCase().indexOf("expression")>-1){
//								writeError(response,str);
//								return;
//							}
//							
//						}
//					}
//					
//				}
			}
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}
	
	private void writeError(ServletResponse res,String str) throws IOException{
		HttpServletResponse response = (HttpServletResponse)res;
		logger.error("非法的字符输入==>"+str);
		response.setStatus(555);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write("系统安全提示：不允许输入含 < >  expression script 等非法字符！");
	}

}
